<?php
class Security 
{
	//error
	var $error = "";
	
	function security()	{
	}
		
	function GetUserRoles($username, $app_id) {
		global $DB;
		//check to see if the user exists
		$DB->query("SELECT * FROM users WHERE username='" . $username . "'");
		//if there is no user store the Security Info and leave
		if($DB->get_num_rows() <= 0)
		{
			$this->error = "userne";
			return "";
		}
		//look up the user's role if any which applies to this application
		$DB->query("SELECT * FROM access WHERE username='" . $username . "' AND AppID='" . $app_id . "'");
		
		if($DB->get_num_rows() <= 0)
		{
			$this->error = "noaccess";
			return "";
		}
		//everything is ok, return the roles
		$roles = array();
		while($row = $DB->fetch_row())
		{
			array_push($roles,$row['RoleID']);
		}
		return $roles;
	}
		
  	function ValidateUser($username, $app_id, $role_id, $show_error = 0) {
		$CurrentUserRoles = $this->GetUserRoles($username, $app_id);

		if($CurrentUserRoles == "")
		{
			switch($this->error)
			{
				case 'userne':
					if($show_error)
					{
						print "<span style='font-size:12px;font-family:Verdana;'>User <strong>" . $username . "</strong> does not exist.  If this user should exist, please contact the administrator of this website.</span>"; 
						break;
					}
					else
					{
						header("Location: index.php?action=logout");
					}
				case 'noaccess':
					if($show_error)
					{
						print "<span style='font-size:12px;font-family:Verdana;'>User <strong>" . $username . "</strong> was not permitted access.  If this user should have access, please contact the administrator of this website.</span>"; 
						break;
					}
					else
					{
						header("Location: index.php?action=logout");
					}
				default:
					if($show_error)
					{
						print "<span style='font-size:12px;font-family:Verdana;'>There was a problem checking security for <strong>" . $username . "</strong>. Please contact the administrator of this website.</span>"; 
						break;
					}
					else
					{
						header("Location: index.php?action=logout");
					}
			}
			exit();
		}
		
		$isValid = false;
		foreach($role_id as $id)
		{ 
			if(in_array($id,$CurrentUserRoles))
			{
				$isValid = true;
			}
		}
		if($isValid)
		{
			return $CurrentUserRoles;
		}
		else
		{
			if($show_error)	
			{
				print '<span class="T1">You do not have rights to this page.<br></span><span class="T1">If you believe this to be an error, please contact your site administrator.</span>';
				exit(); 
			}
			return false;
		}
	}
}	
?>
